<template>
  <view class="edit-page storage-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <uni-forms-item label="配置名称" name="configName" required>
          <uni-easyinput
              v-model="form.configName"
              placeholder="请输入配置名称"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="存储类型" name="storageType" required>
          <BottomSelect
              v-model="form.storageType"
              :options="storageTypeOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择存储类型"
              title="选择存储类型"
              :disabled="mode === 'view'"
              @change="handleStorageTypeChange"/>
        </uni-forms-item>

        <uni-forms-item label="访问地址" name="endpoint" required v-if="form.storageType !== 'local'">
          <uni-easyinput
              v-model="form.endpoint"
              :placeholder="getEndpointPlaceholder()"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="访问密钥" name="accessKey" required v-if="form.storageType !== 'local'">
          <uni-easyinput
              v-model="form.accessKey"
              placeholder="请输入访问密钥"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="私有密钥" name="secretKey" required v-if="form.storageType !== 'local'">
          <uni-easyinput
              v-model="form.secretKey"
              type="password"
              placeholder="请输入私有密钥"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="区域" name="region" required v-if="form.storageType !== 'local'">
          <uni-easyinput
              v-model="form.region"
              placeholder="请输入区域，如：us-east-1"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
        </uni-forms-item>

        <!-- 本地存储说明 -->
        <view class="local-storage-info" v-if="form.storageType === 'local'">
          <uni-icons type="info" size="16" color="#007aff"></uni-icons>
          <text class="info-text">本地文件存储根目录已在服务器配置文件中设置，无需手动配置访问地址。</text>
        </view>

        <uni-forms-item label="存储桶名称" name="bucketName" required>
          <uni-easyinput
              v-model="form.bucketName"
              :placeholder="getBucketPlaceholder()"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
          <text class="form-tip" v-if="form.storageType === 'local'">
            本地存储目录名称，将在根目录下创建此目录
          </text>
        </uni-forms-item>

        <uni-forms-item label="自定义域名" name="domain">
          <uni-easyinput
              v-model="form.domain"
              placeholder="请输入自定义域名（可选）"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="启用HTTPS" name="isHttps">
          <switch
              :checked="form.isHttps === 1"
              @change="handleHttpsChange"
              :disabled="mode === 'view'"/>
        </uni-forms-item>

        <uni-forms-item label="启用直传" name="enableDirectUpload">
          <switch
              :checked="form.enableDirectUpload === 1"
              @change="handleDirectUploadChange"
              :disabled="mode === 'view' || form.storageType === 'local'"/>
          <text class="form-tip" v-if="form.storageType === 'local'">
            本地存储不支持前端直传
          </text>
        </uni-forms-item>

        <uni-forms-item label="令牌过期时间" name="tokenExpireTime" v-if="form.enableDirectUpload === 1">
          <uni-number-box
              v-model="form.tokenExpireTime"
              :min="300"
              :max="86400"
              :disabled="mode === 'view'"/>
          <text class="form-tip">单位：秒，建议设置为 3600（1小时），范围300-86400秒</text>
        </uni-forms-item>

        <uni-forms-item label="最大文件大小" name="maxFileSize">
          <view class="file-size-input">
            <uni-number-box
                v-model="fileSizeValue"
                :min="1"
                :max="1024"
                :disabled="mode === 'view'"/>
            <BottomSelect
                v-model="fileSizeUnit"
                :options="fileSizeUnitOptions"
                value-field="value"
                label-field="text"
                title="选择单位"
                :disabled="mode === 'view'"/>
          </view>
        </uni-forms-item>

        <uni-forms-item label="允许文件类型" name="allowedFileTypes">
          <uni-easyinput
              v-model="form.allowedFileTypes"
              type="textarea"
              placeholder="请输入允许的文件类型，如：.jpg,.png,.pdf"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
          <text class="form-tip">用英文逗号分隔，如：.jpg,.png,.pdf，留空表示不限制</text>
        </uni-forms-item>

        <uni-forms-item label="备注" name="remark">
          <uni-easyinput
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注"
              :disabled="mode === 'view'"
              :clearable="mode !== 'view'">
          </uni-easyinput>
        </uni-forms-item>

      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions" v-if="mode !== 'view'">
      <view class="action-buttons">
        <view class="cancel-btn" @click="handleCancel">取消</view>
        <view class="submit-btn" @click="handleSubmit">
          {{ mode === 'add' ? '确认创建' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, nextTick, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addStorageConfig, getStorageConfig, updateStorageConfig} from '@/api/filemanager/storage'
import {BottomSelect} from '@/components/select'
import {useFileConfigStore} from '@/store/modules/fileConfig'

const {proxy} = getCurrentInstance()
const fileConfigStore = useFileConfigStore()

// 页面参数
const mode = ref('add') // add, edit, view
const configId = ref(null)
const formRef = ref()

// 表单数据
const form = reactive({
  configId: undefined,
  configName: '',
  storageType: '',
  endpoint: '',
  accessKey: '',
  secretKey: '',
  bucketName: '',
  region: '',
  isHttps: 1,
  domain: '',
  enableDirectUpload: 1,
  tokenExpireTime: 3600,
  maxFileSize: 104857600,
  allowedFileTypes: '',
  isDefault: 0,
  remark: ''
})

// 文件大小相关
const fileSizeValue = ref(100)
const fileSizeUnit = ref('MB')

// 存储类型选项
const storageTypeOptions = [
  {value: 'local', text: '本地存储'},
  {value: 'minio', text: 'MinIO'},
  {value: 'aliyun', text: '阿里云OSS'},
  {value: 'tencent', text: '腾讯云COS'},
  {value: 'aws', text: 'AWS S3'}
]

// 文件大小单位选项
const fileSizeUnitOptions = [
  {value: 'KB', text: 'KB'},
  {value: 'MB', text: 'MB'},
  {value: 'GB', text: 'GB'}
]

// 表单验证规则
const rules = reactive({
  configName: {
    rules: [{required: true, errorMessage: '请输入配置名称'}]
  },
  storageType: {
    rules: [{required: true, errorMessage: '请选择存储类型'}]
  },
  endpoint: {
    rules: [{required: true, errorMessage: '请输入访问地址'}]
  },
  accessKey: {
    rules: [{required: true, errorMessage: '请输入访问密钥'}]
  },
  secretKey: {
    rules: [{required: true, errorMessage: '请输入私有密钥'}]
  },
  bucketName: {
    rules: [{required: true, errorMessage: '请输入存储桶名称'}]
  },
  region: {
    rules: [{required: true, errorMessage: '请输入区域'}]
  }
})

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {
  mode.value = options.mode || 'add'
  configId.value = options.configId

  // 设置页面标题
  const titleMap = {
    add: '新增存储配置',
    edit: '编辑存储配置',
    view: '查看存储配置'
  }
  uni.setNavigationBarTitle({
    title: titleMap[mode.value]
  })

  if (mode.value !== 'add' && configId.value) {
    // 延迟加载数据，确保页面完全初始化
    nextTick(() => {
      loadStorageConfig()
    })
  }
})

// 加载存储配置详情
async function loadStorageConfig() {
  try {
    const response = await getStorageConfig(configId.value)
    if (response.code === 200) {
      Object.assign(form, response.data)

      // 转换文件大小显示
      const sizeInfo = bytesToSizeAndUnit(response.data.maxFileSize)
      fileSizeValue.value = sizeInfo.value
      fileSizeUnit.value = sizeInfo.unit
    }
  } catch (error) {
    console.error('加载存储配置失败:', error)
    proxy.$modal.showToast('加载数据失败')
  }
}

// 文件大小转换工具函数
function bytesToSizeAndUnit(bytes) {
  if (!bytes) return {value: 100, unit: 'MB'}

  if (bytes >= 1024 * 1024 * 1024) {
    return {value: Math.round(bytes / (1024 * 1024 * 1024)), unit: 'GB'}
  } else if (bytes >= 1024 * 1024) {
    return {value: Math.round(bytes / (1024 * 1024)), unit: 'MB'}
  } else {
    return {value: Math.round(bytes / 1024), unit: 'KB'}
  }
}

function sizeAndUnitToBytes(value, unit) {
  if (!value) return 104857600 // 默认100MB

  switch (unit) {
    case 'KB':
      return value * 1024
    case 'MB':
      return value * 1024 * 1024
    case 'GB':
      return value * 1024 * 1024 * 1024
    default:
      return value * 1024 * 1024 // 默认MB
  }
}

// 获取端点占位符
function getEndpointPlaceholder() {
  switch (form.storageType) {
    case 'local':
      return '请输入存储根目录，如：/uploads 或 uploads'
    case 'minio':
      return '请输入MinIO访问地址，如：http://localhost:9000'
    case 'aliyun':
      return '请输入阿里云OSS访问地址，如：https://oss-cn-chengdu.aliyuncs.com'
    case 'tencent':
      return '请输入腾讯云COS访问地址，如：https://cos.ap-beijing.myqcloud.com'
    case 'aws':
      return '请输入AWS S3访问地址，如：https://s3.amazonaws.com'
    default:
      return '请输入访问地址'
  }
}

// 获取桶名占位符
function getBucketPlaceholder() {
  switch (form.storageType) {
    case 'local':
      return '请输入目录名称，如：default'
    default:
      return '请输入存储桶名称'
  }
}

// 存储类型变化处理
function handleStorageTypeChange(option) {
  const value = option.value
  if (value === 'local') {
    form.endpoint = ''
    form.accessKey = ''
    form.secretKey = ''
    form.region = ''
    form.enableDirectUpload = 0
    form.isHttps = 0
  } else {
    form.enableDirectUpload = 1
    form.isHttps = 1
  }
}

// 开关变化处理
function handleHttpsChange(event) {
  form.isHttps = event.detail.value ? 1 : 0
}

function handleDirectUploadChange(event) {
  form.enableDirectUpload = event.detail.value ? 1 : 0
}

// 表单验证
function validateForm() {
  if (!form.configName) {
    proxy.$modal.showToast('请输入配置名称')
    return false
  }

  if (!form.storageType) {
    proxy.$modal.showToast('请选择存储类型')
    return false
  }

  if (form.storageType !== 'local') {
    if (!form.endpoint) {
      proxy.$modal.showToast('请输入访问地址')
      return false
    }
    if (!form.accessKey) {
      proxy.$modal.showToast('请输入访问密钥')
      return false
    }
    if (!form.secretKey) {
      proxy.$modal.showToast('请输入私有密钥')
      return false
    }
    if (!form.region) {
      proxy.$modal.showToast('请输入区域')
      return false
    }
  }

  if (!form.bucketName) {
    proxy.$modal.showToast('请输入存储桶名称')
    return false
  }

  return true
}

// 表单提交
async function handleSubmit() {
  try {
    // 表单验证
    await formRef.value.validate()

    // 转换文件大小为字节
    const formData = {...form}
    formData.maxFileSize = sizeAndUnitToBytes(fileSizeValue.value, fileSizeUnit.value)

    let response
    if (mode.value === 'add') {
      response = await addStorageConfig(formData)
      if (response.code === 200) {
        // 添加到缓存
        const newConfig = {...formData, configId: response.data?.configId || Date.now()}
        fileConfigStore.addConfig(newConfig)
        proxy.$modal.showToast('创建成功')
      }
    } else {
      response = await updateStorageConfig(formData)
      if (response.code === 200) {
        // 更新缓存
        fileConfigStore.updateConfig(formData)
        proxy.$modal.showToast('保存成功')
      }
    }

    if (response.code === 200) {
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errorFields) {
      proxy.$modal.showToast('请填写必填项')
    } else {
      proxy.$modal.showToast('操作失败')
    }
  }
}


// 取消
function handleCancel() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';

.local-storage-info {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  background: #f0f8ff;
  border-radius: 6px;
  border: 1px solid #91d5ff;
  margin: 12px 0;

  .info-text {
    margin-left: 8px;
    font-size: 14px;
    color: #666;
    line-height: 1.4;
  }
}

.file-size-input {
  display: flex;
  align-items: center;
  gap: 12px;
}

.form-tip {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

// 额外操作按钮样式已移到通用 edit-page.scss 中
</style>